package cn.pzhu.pserson.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.pzhu.pserson.dto.RulesDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.pzhu.pserson.util.ResponseUtil;
import cn.pzhu.pserson.model.Exhibition;
import cn.pzhu.pserson.service.IExhibitionService;
import cn.pzhu.pserson.dto.LimitShowDTO;
import cn.pzhu.pserson.dto.ExhibitionDTO;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;


@Controller
@RequestMapping("/exhibition")
public class ExhibitionController {
    private  final  static Logger logger = LoggerFactory.getLogger(LogoController.class);
    @Autowired
    private IExhibitionService exhibitionService;

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public ModelAndView list(Model model,
                             @Validated RulesDTO rulesDTO, BindingResult errors){


        ModelAndView view = new ModelAndView("exhibition/add", (Map<String, ?>) model);
        return view;
    }


    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ModelAndView upload(HttpServletRequest request,
                               HttpServletResponse response, MultipartFile file) throws IOException {

        if (file == null) {
            return null;
        }

        String localTempDir = "C:/tomcat/apache-tomcat-8.5.6/webapps/web/img/";
        String fileName = file.getOriginalFilename();
        File tempFile = null;
        try {
            tempFile = new File(localTempDir, "exhibition.png");
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }
            if (!tempFile.exists()) {
                tempFile.createNewFile();
            }
            else{
//                return tempFile;
            }

            file.transferTo(tempFile);
        } catch (Exception e) {
            logger.error("转化图片异常:", e);
        }

        ModelAndView view = new ModelAndView("exhibition/add");
        return view;
    }

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseEntity<String> list(
        @Validated
        LimitShowDTO limitShowDTO, BindingResult errors) {
        if(errors.hasErrors())
            return ResponseUtil.getResponseEntityWhenInvalidReqParams();

        Map<String, Object> result = new HashMap<String, Object>();

        List<Map<String, Object>> exhibitionList = exhibitionService.loadMaps(null, null, null, null, limitShowDTO.getPageNum(), limitShowDTO.getPageSize());
        long count = exhibitionService.count();

        result.put("rows", exhibitionList);
        result.put("total", count);

        return ResponseUtil.getResEntityForGetAndJson(result);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public ResponseEntity<String> show(@PathVariable("id") Integer id) {
        Map<String, Object> exhibitionModel = exhibitionService.findMap(id);

        return ResponseUtil.getResEntityForGetAndJson(exhibitionModel);
    }

    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseEntity<String> create(
        @Validated
        ExhibitionDTO exhibitionDTO, BindingResult errors) {
        if(errors.hasErrors())
            return ResponseUtil.getResponseEntityWhenInvalidReqParams();

        Exhibition exhibitionModel = exhibitionDTO.toModel();

        return ResponseUtil.getResEntityForPPP(exhibitionService.save(exhibitionModel));
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity<String> update(@PathVariable("id") Integer id,
        @Validated
        ExhibitionDTO exhibitionDTO, BindingResult errors) {

        Exhibition exhibitionModel = exhibitionDTO.toModel();
        exhibitionModel.setId(id);
        return ResponseUtil.getResEntityForPPP(exhibitionService.update(exhibitionModel));
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<String> destory(@PathVariable("id") Integer id) {
        return ResponseUtil.getResEntityForDel(exhibitionService.delete(id));
    }

    @RequestMapping(value = "/deletes", method = RequestMethod.DELETE)
    public ResponseEntity<String> deletes(@RequestParam("primaryKeys") Integer[] primaryKeys) {
        return ResponseUtil.getResEntityForDel(exhibitionService.batchDelete(primaryKeys));
    }
}
